<?php

class vietCode {
  /**
   * Load language file (thanks Qaccent - very very old software
   *
   * @param $fileName: Name of language
   * @return unknown
   */
  public $vietchars;
  public static $path;

  public static function getPath() {
    if (!is_null(self::$path)) {
      return self::$path;
    } else {
      return self::$path = dirname(__FILE__);
    }
  }

  public function vietCode($fileName) {
    $this->vietchars = array();
    $f = fopen(self::getPath() . "/vietCode/$fileName.bch", 'rt');
    if ($f===false) return false;
    fgets($f);
    while (!feof($f)) {
      $chars = trim(fgets($f));
      $chars = explode(' ', $chars);
      for ($i=0, $n=count($chars); $i<$n; $i++)
      {
       	$this->vietchars[] = $chars[$i];
      }
    }
  }
};

class vietConvert {
	public $source, $dest;

	public function __construct($source, $dest) {
		$this->source = new vietCode($source);
		$this->dest = new vietCode($dest);
	}

	public function convert($s) {
    return str_replace($this->source->vietchars, $this->dest->vietchars, $s);
  }
  
  public function getJs($isLower=false) {
    $script = "var mapChars = {\n";
    $s = $this->source->vietchars;
    $v = $this->dest->vietchars;
    $n = count($s);
    if ($isLower) {
      for ($i=0; $i<$n; $i++) $v[$i] = strtolower($v[$i]);  
    }
    for ($i=0; $i<$n; $i++) {
      if ($s[$i]!='') {
        $script .= "'{$s[$i]}': '{$v[$i]}',\n";
      }
    }
    $script .= "};
function nomark(s) {
  var b=[], c;
  var n=s.length;
  for (var i=0; i<n; i++) {
    b.push((c=mapChars[s[i]])?c:s[i]);
  }
  return b.join('');
}
";

    return $script;
  }
}
